1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| #include <pthread.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <wait.h>
pthread_mutex_t mutex;
void* another( void* arg ) { printf( "in child thread, lock the mutex\n" ); pthread_mutex_lock( &mutex ); sleep( 5 ); pthread_mutex_unlock( &mutex ); }
void prepare() { pthread_mutex_lock( &mutex ); }
void infork() { pthread_mutex_unlock( &mutex ); }
int main() { pthread_mutex_init( &mutex, NULL ); pthread_t id; pthread_create( &id, NULL, another, NULL ); sleep( 1 ); int pid = fork(); if( pid < 0 ) { pthread_join( id, NULL ); pthread_mutex_destroy( &mutex ); return 1; } else if( pid == 0 ) { printf( "I anm in the child, want to get the lock\n" ); pthread_mutex_lock( &mutex ); printf( "I can not run to here, oop...\n" ); pthread_mutex_unlock( &mutex ); exit( 0 ); } else { pthread_mutex_unlock( &mutex ); wait( NULL ); } pthread_join( id, NULL ); pthread_mutex_destroy( &mutex ); return 0; }
|